package kizzo.game 
{	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import kizzo.game.tile_objects.ActivatorTile;
	import org.flashdevelop.utils.FlashConnect;
	
	public class ActivatorSet extends EventDispatcher
	{
		public var delay:Number;	
		
		private var sequential:Boolean;		
		private var delay_cnt:Number;
		
		private var activators:Vector.<ActivatorTile>;		
		private var update_ticker:Boolean = false;
		
		private var activated_cnt:int;
		private var activated:Boolean;
		
		public static const ACTIVATED:String = "ACTIVATED";
		public static const DEACTIVATED:String = "DEACTIVATED";
		
		
		public function ActivatorSet(sequential:Boolean=true, delay:Number=-1) 
		{			
			this.sequential = sequential;
			
			if (sequential)
				Main.get_instance().addEventListener(TileEvent.MOVE_COMPLETE, move_complete_hnd);
						
			this.delay = delay;
			this.delay_cnt = delay;
			
			this.activators = new Vector.<ActivatorTile>();						
			this.activated_cnt = 0;
			this.activated = false;
		}
		
		
		public function move_complete_hnd(e:Event):void
		{	
			if (!activated)
			{
				if (update_ticker == false && sequential == true)
				{				
					for (var i:int = 0; i < this.activators.length; i++)
						activators[i].deactivate();						
					activated_cnt = 0;
				}
			}
			else
			{
				if (delay_cnt == 0)
				{									
					for (i = 0; i < this.activators.length; i++)
						activators[i].deactivate();						
					activated_cnt = 0;
					
					activated = false;
					
					dispatchEvent(new Event(DEACTIVATED));
				}
				
				if (delay != -1)
					delay_cnt--;
			}
			
			update_ticker = false;
		}
		
		
		public function add_activator(tile:ActivatorTile):void
		{
			this.activators.push(tile);
			
			if (tile.is_turned_on())			
				activated_cnt++;			
			
			tile.addEventListener(TileEvent.CUBE_ON, cube_on_hnd);
			tile.addEventListener(TileEvent.CUBE_OFF, cube_off_hnd);
		}
			
		
		private function cube_on_hnd(e:Event):void
		{
			var tile:ActivatorTile = e.target as ActivatorTile;
			
			if (!tile.is_turned_on())
			{
				tile.activate();	
				activated_cnt++;
				
				if (sequential)
				{
					update_ticker = true;
				}				
			}				
			
			if (activated_cnt == activators.length && !activated)
			{
				activated = true;
				delay_cnt = delay;
				dispatchEvent(new Event(ACTIVATED));				
			}
		}

		
		private function cube_off_hnd(e:Event):void
		{	
			var tile:ActivatorTile = e.target as ActivatorTile;
					
		}				
		
	}

}